//
//  ProgressHUD.m
//  test
//
//  Created by kepuG on 17/1/13.
//  Copyright © 2017年 text. All rights reserved.
//

#import "ProgressHUD.h"


@interface ProgressHUD ()

@property (strong ,nonatomic) UIWindow *window;
@property (strong ,nonatomic) UIView *background;
@property (strong ,nonatomic) UIToolbar *hud;
@property (strong ,nonatomic) UIActivityIndicatorView *spinner;
@property (strong ,nonatomic) UIImageView *image;
@property (strong ,nonatomic) UILabel *label;

@end


@implementation ProgressHUD

+ (ProgressHUD *)shared {
    
    static dispatch_once_t once = 0;
    static ProgressHUD * progressHUD;
    
    dispatch_once(& once , ^{
        progressHUD = [[ProgressHUD alloc] init];
    });
    return progressHUD;
}

-(instancetype)init{
    
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    id<UIApplicationDelegate> delegate = [[UIApplication sharedApplication] delegate];
    
    if ([delegate respondsToSelector:@selector(window)])
        self.window = [delegate performSelector:@selector(window)];
    else self.window = [[UIApplication sharedApplication] keyWindow];
    
    _background = nil ; self.hud = nil ; self.spinner = nil ; self.image = nil; self.label = nil;
    self.alpha = 1.f;
    self.backgroundColor = [UIColor redColor];
    return self;
}

-(void)hudCreate:(NSString *)status image:(UIImage *)image_ spin:(BOOL)spin hide:(BOOL)hide interaction:(BOOL)interaction{
    if (self.hud == nil) {
        self.hud = [[UIToolbar alloc] initWithFrame:CGRectZero];
        self.hud.translucent = YES;
        self.hud.backgroundColor = HUD_BACKGROUND_COLOR;
        self.hud.layer.cornerRadius = 10;
        self.hud.layer.masksToBounds = YES;
        [self registerNotifications];
    }
    if (self.hud.superview == nil) {
        if (interaction == NO) {
            self.background = [[UIView alloc] initWithFrame:self.window.frame];
            self.background.backgroundColor = [UIColor blueColor];
            [self.window addSubview:self.background];
            [self.background addSubview:self.hud];
        }else [self.window addSubview:self.hud];
    }
    
    if (self.spinner == nil) {
        self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        self.spinner.color = HUD_SPINNER_COLOR;
        self.spinner.hidesWhenStopped = YES;
    }
    if (self.spinner.superview == nil) [self.hud addSubview:self.spinner];
    
    if (self.image == nil) {
        self.image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 28, 28)];
    }
    
    if (self.image.superview == nil) [self.hud addSubview:self.image];
    
    if (self.label == nil) {
        self.label = [[UILabel alloc] initWithFrame:CGRectZero];
        self.label.font = HUD_STATUS_FONT;
        self.label.textColor = HUD_STATUS_COLOR;
        self.label.backgroundColor = [UIColor clearColor];
        self.label.textAlignment = NSTextAlignmentCenter;
        self.label.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
        self.label.numberOfLines = 0;
    }
    if (self.label.superview == nil) [self.hud addSubview:self.label];
    
    self.label.text = status;
    self.label.hidden = (status == nil) ? YES : NO ;
    
    self.image.image = image_;
    self.image.hidden = (image_ == nil) ? YES : NO ;
    
    if (spin) [self.spinner startAnimating];  else [self.spinner stopAnimating];
    
    [self hudSize];
    [self hudPosition:nil];
    [self hudShow];
}

-(void)hudShow{

    if (self.alpha == 0) {
        self.alpha = 1;
        self.hud = 0;
        self.hud.transform = CGAffineTransformScale(self.hud.transform, 1.4, 1.4);
        NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseOut;
        
        [UIView animateWithDuration:0.15 delay:0 options:options animations:^{
            
            self.hud.transform = CGAffineTransformScale(self.hud.transform, 1/1.4, 1/1.4);
            self.hud.alpha = 1;
        } completion:nil];
    }
}


- (void)hudHide
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    if (self.alpha == 1)
    {
        NSUInteger options = UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveEaseIn;
        [UIView animateWithDuration:0.15 delay:0 options:options animations:^{
            self.hud.transform = CGAffineTransformScale(self.hud.transform, 0.7, 0.7);
            self.hud.alpha = 0;
        }
                         completion:^(BOOL finished) {
                             [self hudDestroy];
                             self.alpha = 0;
                         }];
    }
}

- (void)hudDestroy
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    [self.label removeFromSuperview];		self.label = nil;
    [self.image removeFromSuperview];		self.image = nil;
    [self.spinner removeFromSuperview];		self.spinner = nil;
    [self.hud removeFromSuperview];			self.hud = nil;
    [self.background removeFromSuperview];	self.background = nil;
}

+ (void)show {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self shared] hudCreate:nil image:nil spin:YES hide:NO interaction:YES];
    });
}

- (void)timedHide
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    NSTimeInterval delay = self.label.text.length * 0.04 + 0.5;
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^(void){ [self hudHide]; });
}



#pragma mark -size

- (void) hudSize{

    CGRect labelRect = CGRectZero;
    CGFloat hudWidth = 100;   CGFloat hudHeight = 100;
    
    if (self.label.text != nil) {
        
        NSDictionary *attributes = @{NSFontAttributeName:self.label.font};
        NSInteger options = NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
        labelRect = [self.label.text boundingRectWithSize:CGSizeMake(200, 300) options:options attributes:attributes context:NULL];
        
        hudWidth = labelRect.size.width + 50;
        hudHeight = labelRect.size.height + 75;
        
        if (hudHeight < 100) hudHeight = 100;
        if (hudWidth  < 100) hudWidth  = 100;
        
        labelRect.origin.x = (hudWidth - labelRect.size.width) / 2;
        labelRect.origin.y = (hudHeight - labelRect.size.height) / 2 + 25;
    }
    
    self.hud.bounds = CGRectMake(0, 0, hudWidth, hudHeight);

    CGFloat imagex = hudWidth/2;
    CGFloat imagey = (self.label.text == nil) ? hudHeight/2 : 36;
    self.image.center = self.spinner.center = CGPointMake(imagex, imagey);
    
    self.label.frame = labelRect;
}

- (void)hudPosition:(NSNotification *)notification
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    CGFloat heightKeyboard = 0;
    NSTimeInterval duration = 0;
    //---------------------------------------------------------------------------------------------------------------------------------------------
    if (notification != nil)
    {
        NSDictionary *info = [notification userInfo];
        CGRect keyboard = [[info valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        duration = [[info valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        if ((notification.name == UIKeyboardWillShowNotification) || (notification.name == UIKeyboardDidShowNotification))
        {
            heightKeyboard = keyboard.size.height;
        }
    }
    else heightKeyboard = [self keyboardHeight];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    CGRect screen = [UIScreen mainScreen].bounds;
    CGPoint center = CGPointMake(screen.size.width/2, (screen.size.height-heightKeyboard)/2);
    //---------------------------------------------------------------------------------------------------------------------------------------------
    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        self.hud.center = CGPointMake(center.x, center.y);
    } completion:nil];
    //---------------------------------------------------------------------------------------------------------------------------------------------
    if (self.background != nil) self.background.frame = self.window.frame;
}
- (CGFloat)keyboardHeight
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    for (UIWindow *testWindow in [[UIApplication sharedApplication] windows])
    {
        if ([[testWindow class] isEqual:[UIWindow class]] == NO)
        {
            for (UIView *possibleKeyboard in [testWindow subviews])
            {
                if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"])
                {
                    return possibleKeyboard.bounds.size.height;
                }
                else if ([[possibleKeyboard description] hasPrefix:@"<UIInputSetContainerView"])
                {
                    for (UIView *hostKeyboard in [possibleKeyboard subviews])
                    {
                        if ([[hostKeyboard description] hasPrefix:@"<UIInputSetHost"])
                        {
                            return hostKeyboard.frame.size.height;
                        }
                    }
                }
            }
        }
    }
    return 0;
}

+ (void)dismiss
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self shared] hudHide];
    });
}


- (void)registerNotifications {
    



}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
